package com.zues.daiommiddleware.linstener;

import com.alibaba.nls.client.protocol.asr.SpeechTranscriberListener;
import com.alibaba.nls.client.protocol.asr.SpeechTranscriberResponse;
import com.zues.daiommiddleware.controller.WebSocketServer;

/**
 * 语音识别监听器-websocket方案
 *
 * @author: zues
 * @date: 2024/9/6
 */
public class SpeechSocketListener extends SpeechTranscriberListener {

    private final WebSocketServer webSocketServer;

    private final String userId;

    public SpeechSocketListener(WebSocketServer webSocketServer, String userId) {
        this.userId = userId;
        this.webSocketServer = webSocketServer;
    }

    @Override
    public void onTranscriberStart(SpeechTranscriberResponse speechTranscriberResponse) {
    }

    /**
     * 识别出一句话的开始.服务端在识别到一句话的开始时,会返回此消息
     * response.getTaskId()
     * 重要提示： task_id很重要，是调用方和服务端通信的唯一ID标识，当遇到问题时，需要提供此task_id以便排查
     * 每次开启语音识别会生成一个唯一的task_id
     */
    @Override
    public void onSentenceBegin(SpeechTranscriberResponse response) {
//        System.out.println("task_id: " + response.getTaskId() + ", name: " + response.getName() + ", status: " + response.getStatus());
    }

    /**
     * 识别出一句话.服务端会智能断句,当识别到一句话结束时会返回此消息
     */
    @Override
    public void onSentenceEnd(SpeechTranscriberResponse response) {
        // 发送识别结果
        webSocketServer.sendOneMessage(userId, response.getTransSentenceText());
    }

    /**
     * TODO 识别出中间结果.服务端识别出一个字或词时会返回此消息.仅当setEnableIntermediateResult(true)时,才会有此类消息返回
     */
    @Override
    public void onTranscriptionResultChange(SpeechTranscriberResponse response) {
    }

    /**
     * 识别结束.服务端识别结束时会返回此消息
     */
    @Override
    public void onTranscriptionComplete(SpeechTranscriberResponse response) {
//        System.out.println("task_id: " + response.getTaskId() + ", name: " + response.getName() + ", status: " + response.getStatus());
    }

    /**
     * 识别失败.服务端识别失败时,会返回此消息
     */
    @Override
    public void onFail(SpeechTranscriberResponse response) {
        System.out.println("读取发生错误了,task_id: " + response.getTaskId() + ", name: " + response.getName() + ", status: " + response.getStatus());
    }
}
